package com.whxd.oauth.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Desc 为方便测试，假设这里是资源服务访问的接口。并在认证服务中开放了p1权限和资源
 * @Author Mr.Yao
 * @Date 2021/7/30 14:11
 * @Version 1.0
 */
@RestController
public class OrderController {

    @RequestMapping(value = "/login-success",produces = {"text/plain;charset=UTF-8"})
    public String loginSuccess(){
        //提示具体用户名称登录成功
        String username = null;
        /**
         * spring security提供会话管 理，认证通过后将身份信息放入SecurityContextHolder上下文，
         * SecurityContext与当前线程进行绑定，方便获取 用户身份。
         */
        //当前认证通过的用户身份
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //用户身份
        Object principal = authentication.getPrincipal();
        if(principal == null){
            username = "匿名";
        }
        if(principal instanceof UserDetails){
            UserDetails userDetails = (UserDetails) principal;
            username = userDetails.getUsername();
        }else{
            username = principal.toString();
        }
        return username+" 登录成功";
    }

    @GetMapping(value = "/r1")
    @PreAuthorize("hasAnyAuthority('p1')")//拥有p1权限才能访问
    public String r1() {
        return "访问资源1";
    }
}
